package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.domain.StrategyEs;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.repository.IStrategyEsRepository;
import cn.wolfcode.luowowo.search.service.IStrategyEsService;
import cn.wolfcode.luowowo.search.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategyEsServiceImpl implements IStrategyEsService {

    @Autowired
    private IStrategyEsRepository strategyEsRepository;


    @Override
    public void save(StrategyEs strategyEs) {
        strategyEsRepository.save(strategyEs);
    }


    //获取条件分组统计数据的集合
    private List<StatisVO> getStatisVOList(String idField,String nameField,String groupName){
        List<Map<String,Object>> data = new ArrayList<>();
        //分组列对象集合
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");
        idSource.field(idField);
        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");
        nameSource.field(nameField);
        sources.add(idSource);
        sources.add(nameSource);
        //构造分组语法
        CompositeAggregationBuilder compositeAggregationBuilder = new CompositeAggregationBuilder(groupName,sources);
        //es查询语句构建类
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.addAggregation(compositeAggregationBuilder);
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0,1));
        nativeSearchQueryBuilder.withIndices(StrategyEs.INDEX_NAME);
        nativeSearchQueryBuilder.withTypes(StrategyEs.TYPE_NAME);
        //获取分组结果
        AggregatedPage<StrategyEs> search = (AggregatedPage<StrategyEs>) strategyEsRepository.search(nativeSearchQueryBuilder.build());
        InternalComposite themeGroup = search.getAggregations().get(groupName);
        List<StatisVO> voList = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : themeGroup.getBuckets()) {
            Long id = Long.parseLong(bucket.getKey().get("id").toString());
            String name = bucket.getKey().get("name").toString();
            long count = bucket.getDocCount();

            StatisVO statisVO = new StatisVO();
            statisVO.setId(id);
            statisVO.setName(name);
            statisVO.setCount(count);
            voList.add(statisVO);
        }
        //优化1:排序
        //通过collections.sort()方法
        //return
        // >0 表示大于
        // <0 表示小于
        // =0 表示等于
        Collections.sort(voList, new Comparator<StatisVO>() {
            @Override
            public int compare(StatisVO o1, StatisVO o2) {
                //正序
//                Long ret = o1.getCount()-o2.getCount();
                //倒序
                Long ret = o2.getCount()-o1.getCount();
                return ret.intValue();
            }
        });

        return voList;
    }

    @Override
    public List<Map<String, Object>> queryThemeCommend() {

        List<Map<String, Object>> data = new ArrayList<>();

        List<StatisVO> voList = this.getStatisVOList
                ("themeId","themeName","themeGroup");

        //优化2:取前10
        if(voList.size()>10){
            voList = voList.subList(0,10);
        }

        //通过主题目的地的id查询目的地的集合
        Map<String,Object> map = null;
        for (StatisVO vo : voList) {
            map = new HashMap<>();
            map.put("theme",vo);
            List<StatisVO> dests = this.getDestByThemeId(vo.getId());
            map.put("dests",dests);
            data.add(map);
        }
        //封装到data里
        return data;
    }

    private List<StatisVO> getDestByThemeId(Long themeId) {

        List<StatisVO> voList = new ArrayList<>();
        List<StrategyEs> strategyList = strategyEsRepository.findByThemeId(themeId);
        //优化3:目的地去重
        List<String> destNameList = new ArrayList<>();
        for (StrategyEs strategyEs : strategyList) {
            if(!destNameList.contains(strategyEs.getDestName())){
                StatisVO statisVO = new StatisVO();
                statisVO.setId(strategyEs.getId());
                statisVO.setName(strategyEs.getDestName());
                voList.add(statisVO);
                destNameList.add(strategyEs.getDestName());
            }
        }
        return voList;
    }

    @Override
    public List<StatisVO> queryConditionChina() {
        return this.getStatisVOList("provinceId","provinceName","provinceGroup");
    }

    @Override
    public List<StatisVO> queryConditionAbroad() {

        //国外攻略将中国删除.通过迭代器
        List<StatisVO> statisVOList = this.getStatisVOList
                ("countryId", "countryName", "countryGroup");
        Iterator<StatisVO> iterator = statisVOList.iterator();
        while(iterator.hasNext()){
            if("中国".equals(iterator.next().getName())){
                iterator.remove();
            }
        }
        return statisVOList;
    }

    @Override
    public List<StatisVO> queryConditionTheme() {
        return this.getStatisVOList("themeId","themeName","themeGroup");
    }

    @Override
    public Page query(StrategySearchQuery qo) {
        TermQueryBuilder query = null;
        PageRequest of = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, qo.getOrderBy());
        if(qo.getType()==StrategySearchQuery.CONDITION_TYPE_COUNTRY){
            //按国家
            query = QueryBuilders.termQuery("countryId", qo.getTypeValue());
        }else if(qo.getType()==StrategySearchQuery.CONDITION_TYPE_PROVINCE){
            //按省份
            query = QueryBuilders.termQuery("provinceId", qo.getTypeValue());
        }else if(qo.getType()==StrategySearchQuery.CONDITION_TYPE_THEME){
            //按主题
            query = QueryBuilders.termQuery("themeId", qo.getTypeValue());
        }

        if(query == null){
            return strategyEsRepository.findAll(of);
        }else{
            return strategyEsRepository.search(query,of);
        }
    }

    @Override
    public List<StrategyEs> findByDestName(String destName) {
        return strategyEsRepository.findByDestName(destName);
    }

    //    @Override
//    public List<Map<String, Object>> queryThemeCommend() {
//        List<Map<String,Object>> data = new ArrayList<>();
//
//
//        //分组列对象集合
//        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
//        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");
//        idSource.field("themeId");
//        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");
//        nameSource.field("themeName");
//        sources.add(idSource);
//        sources.add(nameSource);
//        //构造分组语法
//        CompositeAggregationBuilder compositeAggregationBuilder = new CompositeAggregationBuilder("themeGroup",sources);
//        //es查询语句构建类
//        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//        nativeSearchQueryBuilder.addAggregation(compositeAggregationBuilder);
//        nativeSearchQueryBuilder.withPageable(PageRequest.of(0,1));
//        nativeSearchQueryBuilder.withIndices(StrategyEs.INDEX_NAME);
//        nativeSearchQueryBuilder.withTypes(StrategyEs.TYPE_NAME);
//        //获取分组结果
//        AggregatedPage<StrategyEs> search = (AggregatedPage<StrategyEs>) strategyEsRepository.search(nativeSearchQueryBuilder.build());
//        InternalComposite themeGroup = search.getAggregations().get("themeGroup");
//        List<StatisVO> voList = new ArrayList<>();
//        for (CompositeAggregation.Bucket bucket : themeGroup.getBuckets()) {
//            Long id = Long.parseLong(bucket.getKey().get("id").toString());
//            String name = bucket.getKey().get("name").toString();
//            long count = bucket.getDocCount();
//
//            StatisVO statisVO = new StatisVO();
//            statisVO.setId(id);
//            statisVO.setName(name);
//            statisVO.setCount(count);
//            voList.add(statisVO);
//        }
//        //优化1:排序
//        //通过collections.sort()方法
//        //return
//        // >0 表示大于
//        // <0 表示小于
//        // =0 表示等于
//        Collections.sort(voList, new Comparator<StatisVO>() {
//            @Override
//            public int compare(StatisVO o1, StatisVO o2) {
//                //正序
////                Long ret = o1.getCount()-o2.getCount();
//                //倒序
//                Long ret = o2.getCount()-o1.getCount();
//                return ret.intValue();
//            }
//        });
//
//        //优化2:取前10
//        if(voList.size()>10){
//            voList = voList.subList(0,10);
//        }
//
//        //通过主题目的地的id查询目的地的集合
//        Map<String,Object> map = null;
//        for (StatisVO vo : voList) {
//            map = new HashMap<>();
//            map.put("theme",vo);
//            List<StatisVO> dests = this.getDestByThemeId(vo.getId());
//            map.put("dests",dests);
//            data.add(map);
//        }
//        //封装到data里
//        return data;
//    }

}
